﻿#include "Spell.h"
#include "Map.h"
#pragma execution_character_set("utf-8")


Spell::Spell(Unit* Holder, int Id)
{
	initWithFile("action/player/attack/normal/normal1_1.png");
	autorelease();
	AttackTimer = 0.5f;
	AttackMovingPos = 30.0f;
	MaxAttackRangeX = 100.0f;
	MaxAttackRangeY = 80.0f;
	m_Holder = Holder;
	m_CheckRange_Box = m_Holder->getBoundingBox();
	Map_Layer::GetInstance()->AddSpellToMap(m_Holder, this);
	CalcAttackRange();
	FillTargetMap();
	DealSpellDamage();
	scheduleUpdate();
}

Spell::~Spell()
{
}

void Spell::ReleaseSpell()
{
	Map_Layer::GetInstance()->RemoveUnitSpellFromMap(m_Holder);
	removeFromParentAndCleanup(true);
}

//void Spell::_ReleaseSpell()
//{
//	removeFromParentAndCleanup(true);
//}

void Spell::DealSpellDamage()
{
	if (!Targets.empty())
	{
		for (int i = 0; i != Targets.size(); i++)
		{
			if (Monster* temp = (Monster*)Targets.at(i))
			{
				if (!temp->IsAlive())
					continue;
				int damage = 100;
				if (Player* _caster = m_Holder->ToPlayer())
				if (_caster->GetTotalValueNumber(Item_Value_Att))
					damage = _caster->GetTotalValueNumber(Item_Value_Att);

				temp->ShowDamageNumber(damage * 0.8 + rand() % damage);
				if (temp->GetHeath() <= damage)
					m_Holder->Kill((Unit*)Targets.at(i));
				else
				{
					temp->SetHeath(temp->GetHeath() - damage);
					temp->SetTarget(m_Holder);
				}
			}
		}
	}
}

bool Spell::IsInSpellRange(CCSprite* Checked)
{
	bool IsInRange = false;

	if (m_CheckRange_Box.intersectsRect(Checked->getBoundingBox()))
		IsInRange = true;

	return IsInRange;
}


void Spell::FillTargetMap()
{
	std::vector<Monster*> NeedCheck = Map_Layer::GetInstance()->GetMonsters();
	if (!NeedCheck.empty())
	{
		for (int i = 0; i != NeedCheck.size(); i++)
		{
			if (Monster* Checked = NeedCheck.at(i))
			{
				if (IsInSpellRange(Checked))
				{
					Targets.push_back(Checked);
				}
			}
		}
	}
}

void Spell::CalcAttackRange()
{
	if (m_Holder->GetFacing() == Left)
		m_CheckRange_Box.origin.x = (m_Holder->getPositionX() - MaxAttackRangeX);
	else
		m_CheckRange_Box.origin.x = m_Holder->getPositionX();
	m_CheckRange_Box.size.width = MaxAttackRangeX;
	m_CheckRange_Box.size.height = getBoundingBox().size.height;

}

void Spell::update(float diff)
{
	if (AttackTimer <= diff)
	{
		//((Player*)m_Holder)->CsstFinsh();
		ReleaseSpell();
	}
	else
		AttackTimer -= diff;
}